﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Xml.Linq;
using ICSharpCode.SharpZipLib.Zip;
using SLBIARVerify.ClassLib;

namespace SLBIARVerify
{
    public partial class BIARReduction : Page, INotifyPropertyChanged
    {

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion


        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
        XNamespace io = "http://enterprise.businessobjects.com/infoobject";

        public BIARReduction()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("", UriKind.Relative));
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (NavigationContext.QueryString.ContainsKey("BIARFileName"))
            {
                SourceBIARFileName = NavigationContext.QueryString["BIARFileName"];
                if (SourceBIARFileName.Length > 0)
                {
                    buttonSearch.IsEnabled = true;
                }
            }
        }

        private string sourceBIARFileName = "";

        public string SourceBIARFileName
        {
            get { return sourceBIARFileName; }
            set
            {
                sourceBIARFileName = value;
                NotifyPropertyChanged("SourceBIARFileName");
            }
        }

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            buttonSearch.IsEnabled = false;

            try
            {
                if (searchText.Text.Trim().Length > 0)
                {
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (isf.FileExists("businessobjects.xml"))
                        {
                            using (IsolatedStorageFileStream stream = isf.OpenFile("businessobjects.xml", FileMode.Open))
                            {
                                XElement rootElement = XElement.Load(stream);

                                IEnumerable<NameCuidType> set = rootElement.Elements()
                                                                    .Where(c => c.Element(io + "Name").Value.ToLower().Contains(searchText.Text.Trim().ToLower()))
                                                                    .Select(c => new ClassLib.NameCuidType
                                                                    {
                                                                        Name = c.Element(io + "Name").Value,
                                                                        Type = c.Attribute(xsi + "type").Value.Split(':')[1],
                                                                        Cuid = c.Element(io + "Cuid").Value,
                                                                        ParentCuid = c.Element(io + "ParentCuid").Value
                                                                    })
                                                                  .OrderBy(c => c.TypeOrderFactor.ToString() + "-" + c.Name)
                                                                  .Select((c, index) => new NameCuidType
                                                                   {
                                                                       Name = c.Name,
                                                                       Type = c.Type,
                                                                       Cuid = c.Cuid,
                                                                       ParentCuid = c.ParentCuid,
                                                                       AlterIndicator = index % 2
                                                                   });
                                listbox.ItemsSource = set;

                            }
                        }
                    }
                }
            }
            finally
            {
                buttonSearch.IsEnabled = true;
            }
        }

        private void searchText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                buttonSearch_Click(null, null);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            NameCuidType item = listbox.SelectedItem as NameCuidType;

            if (item != null)
            {
                if (item != null)
                {
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (isf.FileExists("businessobjects.xml"))
                        {
                            using (IsolatedStorageFileStream stream = isf.OpenFile("businessobjects.xml", FileMode.Open))
                            {
                                XElement rootElement = XElement.Load(stream);

                                TreeWork(rootElement, item.Cuid);

                                testlist.Add(item.Cuid);

                                foreach (string oneCuid in testlist)
                                {
                                    rootElement.Elements().Where(c => c.Element(io + "Cuid").Value == oneCuid).Remove();
                                }

                                foreach (string fileName in isf.GetFileNames())
                                {
                                    foreach (string oneCuid in testlist)
                                    {
                                        if (fileName.Contains(oneCuid))
                                        {
                                            isf.DeleteFile(fileName);
                                            break;

                                        }
                                    }
                                }


                                IEnumerable<NameCuidType> set = rootElement.Elements()
                                      .Where(c => c.Element(io + "Name").Value.ToLower().Contains(searchText.Text.Trim().ToLower()))
                                      .Select(c => new ClassLib.NameCuidType
                                      {
                                          Name = c.Element(io + "Name").Value,
                                          Type = c.Attribute(xsi + "type").Value.Split(':')[1],
                                          Cuid = c.Element(io + "Cuid").Value,
                                          ParentCuid = c.Element(io + "ParentCuid").Value
                                      })
                           .OrderBy(c => c.TypeOrderFactor.ToString() + "-" + c.Name)
                           .Select((c, index) => new NameCuidType
                           {
                               Name = c.Name,
                               Type = c.Type,
                               Cuid = c.Cuid,
                               ParentCuid = c.ParentCuid,
                               AlterIndicator = index % 2
                           });

                                listbox.ItemsSource = set;

                                stream.Position = 0;
                                rootElement.Save(stream);
                                stream.SetLength(stream.Position);
                            }

                        }
                    }
                }
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "BIAR File(*.biar)|*.biar";
                dlg.DefaultExt = "biar";
                if (dlg.ShowDialog() == true)
                {
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (Stream zipedFile = dlg.OpenFile())
                        {
                            using (ZipOutputStream zipStream = new ZipOutputStream(zipedFile))
                            {
                                foreach (string fileName in isf.GetFileNames())
                                {
                                    if (fileName.ToLower().EndsWith("zip"))
                                    {
                                        continue;
                                    }
                                    using (IsolatedStorageFileStream sourceFile = isf.OpenFile(fileName, FileMode.Open))
                                    {
                                        byte[] buffer = new byte[sourceFile.Length];
                                        sourceFile.Read(buffer, 0, buffer.Length);

                                        ZipEntry entry = new ZipEntry(fileName);
                                        zipStream.PutNextEntry(entry);

                                        zipStream.Write(buffer, 0, buffer.Length);
                                    }
                                }
                            }
                        }
                        MessageBox.Show("New BIAR file saved!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Error",MessageBoxButton.OK);
            }
        }

        List<string> testlist = new List<string>();

        void TreeWork(XElement rootElement, string parentCuid)
        {
            foreach (string cuid in rootElement.Elements().Where(c => c.Element(io + "ParentCuid").Value == parentCuid).Select(c => c.Element(io + "Cuid").Value))
            {
                TreeWork(rootElement, cuid);
                testlist.Add(cuid);
            }
        }

        private void listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox tmp = sender as ListBox;
            if (tmp != null)
            {
                NameCuidType obj = tmp.SelectedItem as NameCuidType;
                if (obj != null)
                {

                }
            }
        }

    }
}
